<template>
  <div class="user-management">
    <div class="management-header">
      <h2>👥 用户管理</h2>
      <div class="header-actions">
        <button @click="loadUsers" class="btn btn-secondary">🔄 刷新</button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <input
        v-model="searchQuery"
        type="text"
        class="form-input"
        placeholder="🔍 搜索用户名或邮箱..."
        @input="handleSearch"
      />
      <select v-model="filterRole" @change="handleFilter" class="form-select">
        <option value="">全部角色</option>
        <option value="admin">管理员</option>
        <option value="user">普通用户</option>
      </select>
      <select v-model="filterStatus" @change="handleFilter" class="form-select">
        <option value="">全部状态</option>
        <option value="active">活跃</option>
        <option value="disabled">已禁用</option>
      </select>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-icon">👤</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">总用户数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">✅</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.active }}</div>
          <div class="stat-label">活跃用户</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">👑</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.admins }}</div>
          <div class="stat-label">管理员</div>
        </div>
      </div>
    </div>
    
    <!-- 用户列表 -->
    <div v-if="!loading" class="users-table">
      <table>
        <thead>
          <tr>
            <th>用户</th>
            <th>角色</th>
            <th>状态</th>
            <th>令牌数</th>
            <th>最后登录</th>
            <th>注册时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id">
            <td>
              <div class="user-info">
                <strong>{{ user.username }}</strong>
                <span class="user-email">{{ user.email }}</span>
              </div>
            </td>
            <td>
              <span class="badge" :class="user.role === 'admin' ? 'badge-admin' : 'badge-user'">
                {{ user.role === 'admin' ? '管理员' : '用户' }}
              </span>
            </td>
            <td>
              <span class="badge" :class="user.isActive ? 'badge-success' : 'badge-danger'">
                {{ user.isActive ? '活跃' : '禁用' }}
              </span>
            </td>
            <td>{{ user.tokenCount || 0 }}</td>
            <td>{{ formatDate(user.lastLogin) }}</td>
            <td>{{ formatDate(user.createdAt) }}</td>
            <td>
              <div class="action-btns">
                <button @click="viewUser(user)" class="btn btn-sm" title="查看详情">
                  👁️
                </button>
                <button
                  @click="toggleUserStatus(user)"
                  class="btn btn-sm"
                  :class="user.isActive ? 'btn-warning' : 'btn-success'"
                  :title="user.isActive ? '禁用用户' : '启用用户'"
                >
                  {{ user.isActive ? '🚫' : '✅' }}
                </button>
                <button
                  @click="editUserNotes(user)"
                  class="btn btn-sm btn-secondary"
                  title="编辑备注"
                >
                  📝
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div v-if="users.length === 0" class="empty-state">
        <p>没有找到用户</p>
      </div>
    </div>
    
    <div v-else class="loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 用户详情对话框 -->
    <div v-if="showUserDetail" class="dialog-overlay" @click="showUserDetail = false">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>用户详情</h3>
          <button class="close-btn" @click="showUserDetail = false">×</button>
        </div>
        
        <div v-if="selectedUser" class="dialog-body">
          <div class="detail-row">
            <span class="detail-label">用户名</span>
            <span class="detail-value">{{ selectedUser.username }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">邮箱</span>
            <span class="detail-value">{{ selectedUser.email }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">角色</span>
            <span class="detail-value">
              <span class="badge" :class="selectedUser.role === 'admin' ? 'badge-admin' : 'badge-user'">
                {{ selectedUser.role === 'admin' ? '管理员' : '用户' }}
              </span>
            </span>
          </div>
          <div class="detail-row">
            <span class="detail-label">状态</span>
            <span class="detail-value">
              <span class="badge" :class="selectedUser.isActive ? 'badge-success' : 'badge-danger'">
                {{ selectedUser.isActive ? '活跃' : '禁用' }}
              </span>
            </span>
          </div>
          <div class="detail-row">
            <span class="detail-label">令牌数</span>
            <span class="detail-value">{{ selectedUser.tokenCount || 0 }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">注册时间</span>
            <span class="detail-value">{{ formatDate(selectedUser.createdAt) }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">最后登录</span>
            <span class="detail-value">{{ formatDate(selectedUser.lastLogin) }}</span>
          </div>
          <div v-if="selectedUser.notes" class="detail-row full-width">
            <span class="detail-label">管理员备注</span>
            <span class="detail-value">{{ selectedUser.notes }}</span>
          </div>
        </div>
        
        <div class="dialog-actions">
          <button @click="showUserDetail = false" class="btn btn-secondary">关闭</button>
        </div>
      </div>
    </div>
    
    <!-- 编辑备注对话框 -->
    <div v-if="showNotesDialog" class="dialog-overlay" @click="showNotesDialog = false">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>编辑用户备注</h3>
          <button class="close-btn" @click="showNotesDialog = false">×</button>
        </div>
        
        <div class="dialog-body">
          <p class="dialog-hint">
            为用户 <strong>{{ selectedUser?.username }}</strong> 添加管理员备注（用户不可见）
          </p>
          <textarea
            v-model="notesForm"
            class="form-textarea"
            rows="6"
            placeholder="记录用户的特殊情况、处理记录等..."
          ></textarea>
        </div>
        
        <div class="dialog-actions">
          <button @click="showNotesDialog = false" class="btn btn-secondary">取消</button>
          <button @click="saveUserNotes" class="btn btn-primary">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import api from '@/api';

const loading = ref(false);
const users = ref([]);
const searchQuery = ref('');
const filterRole = ref('');
const filterStatus = ref('');
const showUserDetail = ref(false);
const showNotesDialog = ref(false);
const selectedUser = ref(null);
const notesForm = ref('');

const stats = computed(() => {
  return {
    total: users.value.length,
    active: users.value.filter(u => u.isActive).length,
    admins: users.value.filter(u => u.role === 'admin').length,
  };
});

function formatDate(dateString) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
}

async function loadUsers() {
  loading.value = true;
  try {
    const response = await api.get('/admin/users', {
      params: {
        search: searchQuery.value,
        role: filterRole.value,
        isActive: filterStatus.value === 'active' ? true : filterStatus.value === 'disabled' ? false : undefined,
      },
    });
    users.value = response.data.data.users || response.data.data || [];
  } catch (error) {
    console.error('加载用户失败:', error);
    alert('加载用户列表失败');
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  loadUsers();
}

function handleFilter() {
  loadUsers();
}

function viewUser(user) {
  selectedUser.value = user;
  showUserDetail.value = true;
}

async function toggleUserStatus(user) {
  const action = user.isActive ? '禁用' : '启用';
  if (!confirm(`确定要${action}用户 ${user.username} 吗？`)) return;
  
  try {
    const endpoint = user.isActive 
      ? `/admin/users/${user.id}/disable`
      : `/admin/users/${user.id}/enable`;
    
    await api.patch(endpoint);
    user.isActive = !user.isActive;
    alert(`用户已${action}`);
  } catch (error) {
    alert('操作失败: ' + (error.response?.data?.error?.message || error.message));
  }
}

function editUserNotes(user) {
  selectedUser.value = user;
  notesForm.value = user.notes || '';
  showNotesDialog.value = true;
}

async function saveUserNotes() {
  if (!selectedUser.value) return;
  
  try {
    await api.put(`/admin/users/${selectedUser.value.id}/notes`, {
      notes: notesForm.value,
    });
    
    selectedUser.value.notes = notesForm.value;
    
    // 更新列表中的用户
    const index = users.value.findIndex(u => u.id === selectedUser.value.id);
    if (index !== -1) {
      users.value[index].notes = notesForm.value;
    }
    
    showNotesDialog.value = false;
    alert('备注已保存');
  } catch (error) {
    alert('保存失败: ' + (error.response?.data?.error?.message || error.message));
  }
}

onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.user-management {
  background: var(--bg-color, #fff);
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.management-header h2 {
  font-size: 24px;
  color: var(--text-color, #333);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.form-input {
  flex: 1;
  padding: 10px 14px;
  border: 1px solid var(--border-color, #d1d5db);
  border-radius: 8px;
  font-size: 15px;
  color: var(--text-color, #333);
  background: var(--bg-color, #fff);
}

.form-select {
  min-width: 140px;
  padding: 10px 14px;
  border: 1px solid var(--border-color, #d1d5db);
  border-radius: 8px;
  font-size: 15px;
  color: var(--text-color, #333);
  background: var(--bg-color, #fff);
  cursor: pointer;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: var(--bg-secondary, #f9fafb);
  border-radius: 8px;
}

.stat-icon {
  font-size: 32px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: var(--primary-color, #3b82f6);
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary, #6b7280);
}

.users-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background: var(--bg-secondary, #f9fafb);
}

th {
  padding: 12px;
  text-align: left;
  font-weight: 600;
  color: var(--text-color, #333);
  border-bottom: 2px solid var(--border-color, #e5e7eb);
}

td {
  padding: 12px;
  border-bottom: 1px solid var(--border-color, #e5e7eb);
}

tr:hover {
  background: var(--bg-secondary, #f9fafb);
}

.user-info strong {
  display: block;
  color: var(--text-color, #333);
  margin-bottom: 4px;
}

.user-email {
  font-size: 13px;
  color: var(--text-secondary, #6b7280);
}

.badge {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.badge-admin {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.badge-user {
  background: var(--bg-secondary, #f3f4f6);
  color: var(--text-color, #333);
}

.badge-success {
  background: #10b981;
  color: white;
}

.badge-danger {
  background: #ef4444;
  color: white;
}

.action-btns {
  display: flex;
  gap: 6px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-sm {
  padding: 6px 10px;
  font-size: 16px;
}

.btn-primary {
  background: var(--primary-color, #3b82f6);
  color: white;
}

.btn-primary:hover {
  background: var(--primary-dark, #2563eb);
}

.btn-secondary {
  background: var(--bg-secondary, #f3f4f6);
  color: var(--text-color, #333);
}

.btn-secondary:hover {
  background: var(--border-color, #e5e7eb);
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-success {
  background: #10b981;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--text-secondary, #6b7280);
}

.loading {
  text-align: center;
  padding: 60px 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 16px;
  border: 4px solid var(--bg-secondary, #f3f4f6);
  border-top-color: var(--primary-color, #3b82f6);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: var(--bg-color, #fff);
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color, #e5e7eb);
}

.dialog-header h3 {
  margin: 0;
  font-size: 20px;
  color: var(--text-color, #333);
}

.close-btn {
  background: none;
  border: none;
  font-size: 32px;
  color: var(--text-secondary, #666);
  cursor: pointer;
  padding: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  transition: all 0.2s;
}

.close-btn:hover {
  background: var(--bg-secondary, #f3f4f6);
}

.dialog-body {
  padding: 24px;
}

.dialog-hint {
  color: var(--text-secondary, #6b7280);
  margin-bottom: 16px;
  line-height: 1.6;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid var(--border-color, #e5e7eb);
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-row.full-width {
  flex-direction: column;
  gap: 8px;
}

.detail-label {
  font-weight: 500;
  color: var(--text-secondary, #6b7280);
}

.detail-value {
  color: var(--text-color, #333);
}

.form-textarea {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid var(--border-color, #d1d5db);
  border-radius: 8px;
  font-size: 15px;
  color: var(--text-color, #333);
  background: var(--bg-color, #fff);
  font-family: inherit;
  line-height: 1.5;
  resize: vertical;
}

.dialog-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding: 16px 24px;
  border-top: 1px solid var(--border-color, #e5e7eb);
}

/* 深色模式 */
.dark-theme .user-management {
  background: #1f2937;
}

.dark-theme thead {
  background: #111827;
}

.dark-theme tr:hover {
  background: #111827;
}

.dark-theme .stat-card {
  background: #111827;
}

.dark-theme .badge-user {
  background: #374151;
  color: #e5e7eb;
}

.dark-theme .dialog {
  background: #1f2937;
}

.dark-theme .dialog-header,
.dark-theme .dialog-actions {
  border-color: #374151;
}

.dark-theme .detail-row {
  border-bottom-color: #374151;
}

.dark-theme .form-input,
.dark-theme .form-select,
.dark-theme .form-textarea {
  background: #111827;
  border-color: #374151;
  color: #e5e7eb;
}

/* 响应式 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
  }
  
  .form-select {
    width: 100%;
  }
  
  .users-table {
    overflow-x: scroll;
  }
  
  table {
    min-width: 900px;
  }
}
</style>


